package org.liang.family_manager.controller;

import lombok.AllArgsConstructor;
import org.liang.family_manager.controller.vo.MemberForm;
import org.liang.family_manager.dao.po.FamilyMember;
import org.liang.family_manager.dao.po.FamilyAdmin;
import org.liang.family_manager.dao.repo.FamilyAdminRepository;
import org.liang.family_manager.dao.repo.FamilyMemberRepository;
import org.liang.family_manager.service.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/admin")
@AllArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {
    private final FamilyMemberRepository familyMemberRepository;
    private final FamilyAdminRepository familyAdminRepository;
    private final FileStorageService fileStorageService;
    @GetMapping("/members")
    public String manageMembers(Model model, Authentication authentication) {
        // 1. 获取当前登录管理员所属的familyId
        String username = authentication.getName();
        Long familyId = familyAdminRepository.findByUsername(username)
                .orElseThrow()
                .getId();

        // 2. 查询该家族下的所有成员
        List<FamilyMember> members = familyMemberRepository.findByFamilyId(familyId);

        // 3. 传递给模板
        model.addAttribute("members", members);
        FamilyMember member = new FamilyMember();
        model.addAttribute("member", member);
        return "admin/members";
    }
    @GetMapping("/members/{id}")
    @ResponseBody
    public FamilyMember getMember(@PathVariable Long id) {
        return familyMemberRepository.findById(id).orElseThrow();
    }

    @PostMapping("/members")
    public String addMember(@RequestParam String name,
                            @RequestParam String contactInfo,
                            @RequestParam String personalDescription,
                            @RequestParam( name = "avatarUrl", required = false) MultipartFile avatarUrl,
                            RedirectAttributes redirectAttributes,
                            Authentication authentication) {

        FamilyMember member = new FamilyMember();
        member.setName(name);
        member.setContactInfo(contactInfo);
        member.setPersonalDescription(personalDescription);
        String username = authentication.getName();
        FamilyAdmin admin = familyAdminRepository.findByUsername(username)
                .orElseThrow(() -> new IllegalStateException("管理员不存在"));
        member.setFamilyId(admin.getId());
        familyMemberRepository.save(member);


        // 2. 处理照片上传
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            String imageUrl = null;
            try {
                if (!avatarUrl.getContentType().startsWith("image/")) {
                    throw new IllegalArgumentException("只允许上传图片");
                }
                imageUrl = fileStorageService.storeFile(avatarUrl, member.getId());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            member.setAvatarUrl(imageUrl);
            familyMemberRepository.save(member);
        }


        redirectAttributes.addFlashAttribute("successMessage", "成员添加成功");
        return "redirect:/admin/members";
    }

    @PutMapping("/members/{id}")
    public String updateMember(
            @PathVariable Long id,
            @ModelAttribute MemberForm form,
            RedirectAttributes redirectAttributes) {

        FamilyMember member = familyMemberRepository.findById(id).orElseThrow();
        member.setName(form.getName());
        member.setContactInfo(form.getContactInfo());
        member.setPersonalDescription(form.getPersonalDescription());
        member.setFamilyId(id);
        member.setPassword(form.getPassword());
        // 更新其他字段...
        familyMemberRepository.save(member);

        redirectAttributes.addFlashAttribute("success", "修改成功");
        return "redirect:/admin/members";
    }


    @DeleteMapping("/members/{id}")
    public String deleteMember(
            @PathVariable Long id,
            Authentication authentication) {

//        // 获取当前用户的家族ID
//        Long currentFamilyId = getCurrentFamilyId(authentication);
//
//        // 校验成员是否属于当前家族
//        FamilyMember member = memberRepository.findById(id).orElseThrow();
//        if (!member.getFamilyId().equals(currentFamilyId)) {
//            return ResponseEntity.status(403).body("无权操作");
//        }

        familyMemberRepository.deleteById(id);
        return "redirect:/admin/members";
    }
    
    @GetMapping("/relations")
    public String manageRelations() {
        return "admin/relations";
    }
}